<?php
// 应用公共文件

use app\admin\service\AuthService;
use app\common\SmsDemo;


    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {

        return url($url, $vars, $suffix, $domain)->build();
    }

    /*导出大量数据至csv*/
    function excelFileExport($data=[],$title='',$tableheader)
    {
        ini_set('max_execution_time', 300);// 设置PHP超时时间
        ini_set('memory_limit', '2048M');// 设置PHP临时允许内存大小
        $queryResult = $data;

        //路径
        $fileName =$title . date('Ymd_His') . '.csv';
        $filePath = 'excel/' . $fileName;
        $index = 0;
        $fp = fopen($filePath, 'w'); //生成临时文件
        chmod($filePath, 0777);//修改可执行权限
        // 将数据通过fputcsv写到文件句柄
        $header = $tableheader;//设置表头
        fputcsv($fp, $header);
        //处理导出数据
        foreach ($queryResult as $key => &$val) {
            foreach ($val as $k => $v) {
                $val[$k] = $v . "\t";
                if ($index == 10000) { //每次写入1000条数据清除内存
                    $index = 0;
                    ob_flush();//清除内存
                    flush();
                }
                $index++;
            }
            fputcsv($fp, $val);
        }
        ob_flush();
        fclose($fp);  //关闭句柄
        header("Cache-Control: max-age=0");
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($fileName));
        header("Content-Type: text/csv");
        header("Content-Transfer-Encoding: binary");
        header('Content-Length: ' . filesize($filePath));
        @readfile($filePath);//输出文件;
        unlink($filePath); //删除压缩包临时文件
        echo $filePath;
        return;
    }
/**
 * 计算时间间隔
 * @param $date
 * @return string
 */
    function formatTime($date) {
        $str = '';
        //$timer = strtotime($date);
        $timer = $date;
        $diff = $_SERVER['REQUEST_TIME'] - $timer;
        $day = floor($diff / 86400);
        $free = $diff % 86400;
        if($day > 0) {
            return $day."天前";
        }else{
            if($free>0){
                $hour = floor($free / 3600);
                $free = $free % 3600;
                if($hour>0){
                    return $hour."小时前";
                }else{
                    if($free>0){
                        $min = floor($free / 60);
                        $free = $free % 60;
                        if($min>0){
                            return $min."分钟前";
                        }else{
                            if($free>0){
                                return $free."秒前";
                            }else{
                                return '刚刚';
                            }
                        }
                    }else{
                        return '刚刚';
                    }
                }
            }else{
                return '刚刚';
            }
        }
    }


    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }





    /**
     * debug调试
     * @param string|array $data 打印信息
     * @param string $type 类型
     * @param string $suffix 文件后缀名
     * @param bool $force
     * @param null $file
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/');
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND);
        $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }


if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null $name
     * @return array|mixed
     */

}



    /**
     * 二位数组重新组合数据
     * @param $array
     * @param $key
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }



    /**
     * auth权限验证
     * @param $node
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {

        $authService = new AuthService(session('admin.id'));
        $check = $authService->checkNode($node);
        $check ? $re = '' : $re = 'layui-hide';

        return $re;
    }
//助手函数 mongoDB

if (!function_exists('mongoDB')) {
    /**
     * 获取容器对象实例
     * @return Container
     */
    function mongo($table) {

        return  \think\facade\Db::connect('mongo')->table($table);
    }
}

/**
 * @param $phone
 * @param $days
 * @param $template
 * @return mixed
 * 短信验证
 */
function smsdemo($phone,$days,$template){
    $sms = new SmsDemo();
    $message = $sms->sendSms($phone,$days,$template);
    return $message;
}
/**
 * Return the remainder of a string after the first occurrence of a given value.
 *
 * @param  string  $subject
 * @param  string  $search
 * @return string
 */
function after($subject, $search){
    return $search === '' ? $subject : array_reverse(explode($search, $subject, 2))[0];
}

/**
 * Get the portion of a string before the first occurrence of a given value.
 *
 * @param  string  $subject
 * @param  string  $search
 * @return string
 */
function before($subject, $search)
{
    return $search === '' ? $subject : explode($search, $subject)[0];
}
/*
 * 订阅过期回调方法
 */


function keyCallback($redis, $pattern, $chan, $msg){
    $this->advert =   app('app\common\model\banner\Advert');
    $this->advert->where('id',2)->save(['sort'=>10]);
        echo "Pattern: $pattern\n";
        echo "Channel: $chan\n";
        echo "Payload: $msg\n";
        //keyCallback为订阅事件后的回调函数，这里写业务处理逻辑，
        $order = explode('-', $msg);
        echo "订单号：" . $order[1] . "\n";
        echo "表名：" . $order[3] . "\n";
        echo "字段：" . $order[5] . "\n";
}
